<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px"
        ></span>
        配置会员等级
      </p>
      <p slot="extra" style="color: #999; font-size: 12px">
        <label style="color: #ff3b30">*</label> 为必填
      </p>

      <Form
        ref="formValidate2"
        :model="bloc.model"
        :rules="ruleValidate3"
        :label-width="111"
        style="padding: 50px 10% 0 10%; width: 860px"
      >
        <FormItem label="会员等级:" prop="lv" style="color: #ff9900" required>
          {{ "LV" + bloc.model.lv }}
        </FormItem>

        <FormItem label="等级名称:" prop="name" required>
          <Input
            v-model="bloc.model.name"
            placeholder="最多10个字"
            style="width: 300px"
            :maxlength="10"
          />
        </FormItem>

        <FormItem label="升级条件:" prop="upgradeCondition" required>
          <!--          <div v-for="(value, index) in bloc.conditionList" :key="index">-->
          <CheckboxGroup size="large" class="item-box" v-model="bloc.condition">
            <div
              v-for="num in Math.ceil(bloc.conditionList.length / 2)"
              :key="num"
              class="condition-group-column"
            >
              <!--            <template style="display: flex;flex-direction: column">-->
              <Checkbox
                v-for="condition in handleConditionsList(
                  num,
                  bloc.conditionList.length
                )"
                :label="condition.conditionname"
                :key="condition.id"
              >
                <span style="margin-left: 5px; width: 100px">{{
                  condition.conditionname
                }}</span>
              </Checkbox>
            </div>
            <!--            </template>-->
          </CheckboxGroup>
          <!--          </div>-->
          <Input
            v-model="bloc.model.upgradeCondition"
            placeholder="请输入"
            style="width: 200px; margin-top: 30px"
          />
        </FormItem>

        <FormItem label="升级礼包:" required>
          <!--          <div v-for="(value, index) in bloc.conditionList" :key="index">-->
          <CheckboxGroup size="large" class="item-box" v-model="bloc.gift">
            <div
              v-for="num in Math.ceil(bloc.giftList.length / 2)"
              :key="num"
              class="gift-group-column"
            >
              <!--              <template style="display: flex;flex-direction: column">-->
              <Checkbox
                v-for="gift in handleGiftsList(num, bloc.giftList.length)"
                :label="gift.giftname"
                :key="gift.id"
                style="margin-bottom: 30px"
              >
                <span style="margin-left: 5px; width: 100px">
                  {{ gift.giftname }}
                  <input
                    v-if="gift.id === 1"
                    v-model="bloc.model.upgradePoint"
                    placeholder="请输入积分数值"
                    style="
                      width: 185px;
                      margin-top: 30px;
                      margin-left: 22px;
                      padding-left: 8px;
                      border: #e1e1e1 1px solid;
                      outline: none;
                    "
                  />
                  <span v-if="gift.id === 1" class="unit">分</span>
                  <span
                    v-else-if="gift.id !== 1"
                    v-for="product in bloc.thingList"
                    :key="product.giftId"
                    class="gift-group-column"
                  >
                    <span style="padding-left: 100px">
                      <b v-if="product.num !== 0">
                        {{
                          product.sortName +
                          " " +
                          product.modelName +
                          " " +
                          product.productNumber +
                          " x " +
                          product.num
                        }}
                      </b>
                      <Button size="small" @click="edit(product.giftId)"
                        >配置奖励
                      </Button>
                    </span>
                  </span>
                </span>
              </Checkbox>
            </div>
          </CheckboxGroup>
          <Modal title="配置奖励" v-model="visible1">
            <Form
              ref="formValidate5"
              :model="bloc.editModel"
              :rules="ruleValidate4"
              :label-width="111"
              style="width: 860px"
            >
              <FormItem label="实物分类:" prop="categoryId" required>
                <i-select
                  v-model="bloc.editModel.categoryId"
                  filterable
                  style="width: 350px"
                  @on-change="(value) => CategoryChange(value)"
                >
                  <i-option
                    v-for="item in bloc.a.items"
                    :value="item.categoryId"
                    :key="item.categoryId"
                    >{{ item.sortName }}</i-option
                  >
                </i-select>
              </FormItem>
              <FormItem label="实物型号:" prop="modelId" required>
                <i-select
                  v-model="bloc.editModel.modelId"
                  filterable
                  style="width: 350px"
                  @on-change="(value) => ModelChange(value)"
                >
                  <i-option
                    v-for="item in bloc.b.items"
                    :value="item.modelId"
                    :key="item.modelId"
                    >{{ item.modelName }}</i-option
                  >
                </i-select>
              </FormItem>
              <FormItem label="实物品号:" prop="productId" required>
                <i-select
                  v-model="bloc.editModel.productId"
                  filterable
                  style="width: 350px"
                >
                  <i-option
                    v-for="item in bloc.c.items"
                    :value="item.productId"
                    :key="item.productId"
                    >{{ item.productNumber }}</i-option
                  >
                </i-select>
              </FormItem>
              <FormItem label="实物数量:" prop="num" required>
                <div style="float: left; display: inline-block">
                  <Input
                    v-model="bloc.editModel.num"
                    :maxlength="2"
                    style="width: 350px"
                  />
                  <span class="unit">份</span>
                </div>
              </FormItem>
              <!--              <FormItem label="有效期:" prop="exp" required>-->
              <!--                <div style="float: left;display: inline-block">-->
              <!--                  <Input v-model="bloc.editModel.exp" :maxlength="5" style = 'width: 350px'/>-->
              <!--                  <span class="unit">天</span>-->
              <!--                </div>-->
              <!--              </FormItem>-->
            </Form>
            <div slot="footer">
              <AppButton
                ref="save"
                type="primary"
                @click="editJoin('formValidate5')"
                >确定</AppButton
              >
            </div>
          </Modal>
        </FormItem>

        <FormItem
          label="会员卡图片:"
          prop="memberCard"
          required
          style="margin-top: 55px"
        >
          <div
            class="demo-upload-list"
            v-for="(item, index) in fileList"
            :key="index"
          >
            <template v-if="item.status1 === 'finished'">
              <img :src="item.memberCard" />
              <div class="demo-upload-list-cover">
                <Icon
                  type="ios-eye-outline"
                  @click.native="handleView(item.memberCard)"
                ></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click.native="handleRemove(item)"
                ></Icon>
              </div>
            </template>
            <template v-else>
              <Progress
                v-if="item.showProgress"
                :percent="item.percentage"
                hide-info
              ></Progress>
            </template>
          </div>
          <Upload
            ref="upload"
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="2048"
            :format="['jpg', 'png', 'gif']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="handleMaxSize1"
            :on-success="handleSuccess"
            style="display: inline-block; width: 58px; margin-left: 15px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%" />
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG、GIF格式，图片小于2M</p>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px">
        <Button style="width: 100px; height: 40px" @click="handleCancel()"
          >返回</Button
        >
        <AppButton
          ref="save"
          style="margin-left: 30px; width: 100px; height: 40px"
          type="primary"
          :disabled="bloc.isDetail"
          @click="saveEdit('formValidate2')"
          >保存
        </AppButton>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { store } from "@/store/Store";
import { baseUrl } from "@/base/Request";
import { Route } from "vue-router";
import { FormBloc } from "./EditBloc";
import { isEmpty } from "@/base/util/Strings";
import { AppButton } from "@/type/AppButton";
import { deepAssign } from "@/base/util/Objects";
import { Loading } from "@/base/Loading";
@Component({
  components: {},
})
export default class extends Vue {
  disabled: boolean = true;
  bloc = new FormBloc();
  beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
    next((vm) => {
      vm.bloc.model.lv = vm.idx;
      vm.bloc.fileList = [];
      vm.bloc.fileList.push(vm.bloc.model.memberCard);
      vm.bloc.condition = [];
      if (vm.bloc.model.upgradeCondition === 0) {
        vm.bloc.condition.push("会员注册");
      } else {
        vm.bloc.condition.push("成长值");
      }
      if (vm.bloc.model.upgradePoint !== 0) {
        vm.bloc.gift.push("送积分");
      }
      if (vm.bloc.model.upgradeGift !== 0) {
        vm.bloc.gift.push("送实物");
      }
      vm.bloc.getGift(vm.bloc.model.lv);
      vm.bloc.getCategory();
    });
  }

  validateCondition = (rule: any, value: string, callback: any) => {
    if (this.bloc.condition.length === 1) {
      if (this.bloc.condition[0] === "成长值") {
        this.bloc.model.upgradeCondition === 0 ||
        isNaN(this.bloc.model.upgradeCondition)
          ? callback(new Error("请输入一个不为0的值"))
          : callback();
      } else {
        callback();
      }
    } else {
      callback(new Error("升级条件有且只能选择一项！"));
    }
  };

  get idx() {
    let routeParams = {};
    Object.keys(this.$route.query).forEach((item) => {
      routeParams[item] = this.$route.query[item];
      // eslint-disable-next-line camelcase
      let json_maintain = JSON.parse(routeParams[item]);
      deepAssign(this.bloc.model, json_maintain);
    });
    return this.bloc.model.lv;
  }
  get uploadHeaders() {
    return {
      Authorization: "Bearer " + store.state.auth.accessToken,
    };
  }
  get uploadAction() {
    return `${baseUrl}/api/upload/image`;
  }
  imgUrl = "";
  visible = false;
  visible1 = false;
  btnload = new Loading();
  get fileList() {
    return this.bloc.fileList.map((x) => {
      return { name: "name", memberCard: x, status1: "finished" };
    });
  }
  handleView(url) {
    this.imgUrl = url;
    this.visible = true;
  }
  handleRemove(file) {
    this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
  }
  edit(key) {
    // 点击修改,触发弹窗
    if (key) {
      this.bloc.tempArr = [];
      this.bloc.tempArr = this.bloc.getThelement(key);
      this.bloc.editModel.categoryId = this.bloc.getCategoryId(
        this.bloc.tempArr["sortName"]
      );
      if (
        this.bloc.editModel.categoryId !== "" &&
        this.bloc.editModel.categoryId
      ) {
        this.bloc.getAllModel(this.bloc.editModel.categoryId).then((res) => {
          this.bloc.editModel.modelId = this.bloc.getModelId(
            this.bloc.tempArr["modelName"],
            res
          );
          if (
            this.bloc.editModel.modelId &&
            this.bloc.editModel.modelId !== "" &&
            this.bloc.editModel.modelId !== "0"
          ) {
            this.bloc.getAllProduct(this.bloc.editModel.modelId).then((res) => {
              this.bloc.editModel.productId = this.bloc.getProductId(
                this.bloc.tempArr["productNumber"],
                res
              );
            });
          }
        });
      }
      this.bloc.editModel.num = this.bloc.tempArr["num"];
    }
    this.visible1 = true;
  }
  CategoryChange(value) {
    this.bloc.getAllModel(value).catch((e) => {
      this.bloc.b = { items: [] };
      this.bloc.editModel.modelId = "0";
      this.$Message.error("当前分类下没有对应的型号");
    });
  }
  ModelChange(value) {
    this.bloc.getAllProduct(value).catch((e) => {
      this.bloc.c = { items: [] };
      this.bloc.editModel.productId = "0";
      this.$Message.error("当前型号下没有对应的品号");
    });
  }
  editJoin(name) {
    // 修改弹窗返回页面
    this.$refs[name].validate((valid) => {
      if (valid) {
        this.btnload.loading = true;
        this.bloc.thingList.splice(
          this.bloc.thingList.indexOf(this.bloc.tempArr),
          1
        );
        this.bloc.thingList.push({
          sortName: this.bloc.editModel.a_sortName,
          modelName: this.bloc.editModel.b_modelName,
          productNumber: this.bloc.editModel.c_ProductNumber,
          num: this.bloc.editModel.num,
          exp: this.bloc.editModel.exp,
        });
        if (this.bloc.gift.indexOf("送实物") === -1) {
          this.bloc.gift.push("送实物");
        }
        this.bloc.model.upgradeGift = 1;
        this.btnload.loading = false;
        this.visible1 = false;
      }
    });
  }

  ruleValidate3: any = {
    upgradeCondition: [{ validator: this.validateCondition, trigger: "blur" }],
    memberCard: [
      { required: true, message: "会员卡图片不能为空", trigger: "change" },
    ],
    name: [{ required: true, message: "等级名称不能为空", trigger: "blur" }],
  };
  validateNum = (rule, value, callback) => {
    if (value === undefined) {
      callback(new Error("数量不能为空"));
    } else {
      let reg2 = /^[+]?(([1-9]*$))/;
      if (!reg2.test(value)) {
        callback(new Error("请输入正整数"));
      }
      callback();
    }
  };
  // validateExp = (rule, value, callback) => {
  //     if (value === undefined) {
  //         callback(new Error('有效期不能为空'));
  //     } else {
  //         let reg2 = /^[+]?(([1-9]*$))/;
  //         if (!reg2.test(value)) {
  //             callback(new Error('请输入正整数'));
  //         }
  //         callback();
  //     }
  // };
  categoryId = (rule, value, callback) => {
    if (value === undefined || value === "0") {
      callback(new Error("分类不能为空"));
    } else {
      let res = this.bloc.getCategoryName(value);
      if (res === "") {
        callback(new Error("请输入正确的实物分类"));
      } else {
        this.bloc.editModel.a_sortName = res;
      }
      callback();
    }
  };
  modelId = (rule, value, callback) => {
    if (value === undefined || value === "0") {
      callback(new Error("型号不能为空"));
    } else {
      let res = this.bloc.getModelName(value);
      if (res === "") {
        callback(new Error("请输入正确的实物型号"));
      } else {
        this.bloc.editModel.b_modelName = res;
      }
      callback();
    }
  };
  productId = (rule, value, callback) => {
    if (value === undefined || value === "0") {
      callback(new Error("品号不能为空"));
    } else {
      let res = this.bloc.getProductName(value);
      if (res === "") {
        callback(new Error("请输入正确的实物品号"));
      } else {
        this.bloc.editModel.c_ProductNumber = res;
      }
      callback();
    }
  };
  ruleValidate4: any = {
    categoryId: [{ validator: this.categoryId, trigger: "change" }],
    modelId: [{ validator: this.modelId, trigger: "change" }],
    productId: [{ validator: this.productId, trigger: "change" }],
    num: [{ validator: this.validateNum, trigger: "change" }],
    // exp: [{validator: this.validateExp, trigger: 'change'}]
  };
  $refs!: {
    save: AppButton;
    formValidate2: HTMLFormElement;
    formValidate5: HTMLFormElement;
  };
  handleConditionsList(num, lens) {
    let start = (num - 1) * 2;
    let end = num * 2 > lens ? lens : num * 2;
    return this.bloc.conditionList.slice(start, end);
  }
  handleGiftsList(num, lens) {
    let start = (num - 1) * 2;
    let end = num * 2 > lens ? lens : num * 2;
    return this.bloc.giftList.slice(start, end);
  }

  // 保存修改，提交表单
  saveEdit(name) {
    this.$refs[name].validate((valid) => {
      if (valid) {
        this.$refs.save.bloc.loading = true;
        if (this.bloc.condition[0] === "会员注册") {
          this.bloc.model.upgradeCondition = 0;
        }
        if (this.bloc.gift.indexOf("送实物") === -1) {
          this.bloc.model.upgradeGift = 0;
          this.bloc.editModel.a_sortName = "";
          this.bloc.editModel.b_modelName = "";
          this.bloc.editModel.c_ProductNumber = "";
        }
        this.bloc
          .save(this.bloc.model)
          .then((res) => {
            this.$Message.success("保存成功");
            this.$refs.save.bloc.loading = false;
            this.handleCancel();
          })
          .catch((err) => {
            // this.$Message.error('保存失败');
            this.$Message.error(err.message);
            this.$refs.save.bloc.loading = false;
          });
      }
    });
  }

  handleFormatError1(file) {
    this.$Message.error("请选择格式为JPG、PNG、GIF格式的文件");
  }

  handleMaxSize1(file) {
    this.$Message.error("图片大小不能超过2M");
    console.log("test");
  }

  handleSuccess(res, file) {
    this.bloc.model.memberCard = res.data[0];
    if (this.bloc.fileList.length > 0) {
      this.bloc.fileList = [];
    }
    this.bloc.fileList.push(this.bloc.model.memberCard);
  }
  handleCancel() {
    this.$router.push({ path: `/lv` });
  }
}
</script>

<style lang="less" scoped>
span1 {
  color: #ff9900;
}
.benefit-group-column {
  display: flex;
  flex-direction: row;
}
.condition-group-column {
  display: flex;
  flex-direction: column;
}
.gift-group-column {
  display: flex;
  flex-direction: column;
}
.unit {
  height: 38px;
  width: 28px;
  text-align: center;
  background-color: #e1e1e1;
  color: #999999;
  font-size-adjust: initial;
  margin-top: 30px;
}
.ivu-checkbox-wrapper {
  height: 45px;
}

/deep/ .ivu-form-item-content {
  display: flex !important;
  justify-content: start !important;
  align-items: center !important;
}
/deep/ .ivu-form-item-label {
  padding-top: 0px;
}
</style>
